package com.fanjia.taobao.common.util;


import com.fanjia.taobao.user.entity.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtTokenProvider {

    private String header;
    private String secret;
    private long expiration = 7 * 24 * 3600 * 1000;    // 过期时间，单位毫秒
    private final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);


    public String createJwtToken(Authentication authentication) {
        String username = ((User) authentication.getPrincipal()).getUsername();
        Date expireTime = new Date(System.currentTimeMillis() + expiration);

        return Jwts.builder()
                .setSubject(username)
                .setExpiration(expireTime)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 校验token, 如果Jwt可以解析令牌字符串并且不抛出任何异常，则该令牌是合格的
     */
    public boolean validateToken(String token) {
        String VALIDATE_FAILED = "验证失败: ";
        //ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        } catch (Exception ex) {
            logger.error(VALIDATE_FAILED + ex.getMessage());
            return false;
        }
    }
}
